package com.srd.phone.application;

import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.srd.phone.bean.BarrioInfo;
import com.srd.phone.dialog.BarrioDialog;
import com.srd.phone.utils.CommonUtils;
import com.srd.phone.utils.Constants;
import com.srd.phone.utils.LogUtils;
import com.srd.phone.utils.PreferenceUtils;
import com.srd.phone.utils.StorageUtils;

import java.io.InputStream;
import java.util.List;

public class BaseApplication extends Application {

    private RequestQueue requestQueue;
    private static boolean DEBUG = true;

    @Override
    public void onCreate() {
        super.onCreate();
        init();
        configuration();
    }

    private void init() {
        PreferenceUtils.init(this);
        initImageLoader();
//        LeakCanary.install(this); //检测内存泄漏
        new Thread() { //初始化省市区数据
            @Override
            public void run() {
                initDatas();
            }
        }.start();
        //保存当前版本的code值
        PreferenceUtils.getInstance().putData(Constants.PREFERENCE_VERSION_CODE, getVersionCode());





    }

    /**
     * 初始化省市区数据
     */
    protected void initDatas() {
        if (BarrioDialog.mProvinceDatas != null && BarrioDialog.mProvinceDatas.length != 0 && BarrioDialog.mCitisDatasMap.size() != 0 && BarrioDialog.mDistrictDatasMap.size() != 0) {
            return;
        }
        AssetManager asset = getAssets();
        try {
            InputStream input = asset.open("province_data.json");
            String value = CommonUtils.retrieveContent(input);
            List<BarrioInfo> list = BarrioInfo.parser(value);
            BarrioDialog.mProvinceDatas = new BarrioInfo[list.size()];
            for (int i = 0; i < list.size(); i++) {
                BarrioInfo province = list.get(i);
                BarrioDialog.mProvinceDatas[i] = province;
                BarrioInfo[] citys = new BarrioInfo[province.list.size()];
                for (int j = 0; j < province.list.size(); j++) {
                    BarrioInfo city = province.list.get(j);
                    citys[j] = city;
                    BarrioInfo[] districts = new BarrioInfo[city.list.size()];
                    for (int k = 0; k < city.list.size(); k++) {
                        BarrioInfo district = city.list.get(k);
                        districts[k] = district;
                    }
                    BarrioDialog.mDistrictDatasMap.put(city.id, districts);
                }
                BarrioDialog.mCitisDatasMap.put(province.id, citys);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void configuration() {
        LogUtils.setDebug(DEBUG);
    }

    /**
     * 初始化获取RequestQueue
     */
    public RequestQueue getRequestQueue() {
        if (requestQueue == null) {
            requestQueue = Volley.newRequestQueue(this);
        }
        return requestQueue;
    }

    /**
     * 初始化ImageLoader
     */
    private void initImageLoader() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory() //禁止缓存不同尺寸的图片到内存中
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .memoryCache(new WeakMemoryCache())
                .diskCacheSize(50 * 1024 * 1024) // 50 MiB
                .diskCache(new UnlimitedDiskCache(StorageUtils.getCacheFile(this)))
                .defaultDisplayImageOptions(options)
                .tasksProcessingOrder(QueueProcessingType.LIFO);
        ImageLoader.getInstance().init(config.build());
    }

    /**
     * 获取versioncode值
     *
     * @return
     */
    public int getVersionCode() {
        int version = 0;
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
            version = packInfo.versionCode;
            return version;
        } catch (Exception e) {
        }
        return version;
    }

    /*
    *
    * 获取 versionName
    * @return
     * */
    public String getVersionName(){
        String versionName = "";
        try {
            PackageManager packageManager = getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
            versionName = packInfo.versionName;
        } catch (Exception e) {
        }
        return versionName;
    }

    private void configShare(){

//            //配置所有的分享方式
//            LinkedHashMap<SHARE_MEDIA,Integer>iconMap = new LinkedHashMap<>();
//            iconMap.put(SHARE_MEDIA.WEICHAT, R.drawable.share_weixin);
//            iconMap.put(SHARE_MEDIA.WEICHATCIRCLE,R.drawable.share_momment);
//            iconMap.put(SHARE_MEDIA.SINA,R.drawable.share_sina);
//            iconMap.put(SHARE_MEDIA.QQ,R.drawable.share_qq);
//            iconMap.put(SHARE_MEDIA.QQZONE,R.drawable.share_qzeon);
//            iconMap.put(SHARE_MEDIA.MESSAGE, R.drawable.share_message);
//
//            //初始化分享相关的key、appId 信息
//            ShareManager.init()
//                    //应用的名字
//                    .setAppName("test")
//                    .setDefShareImageUrl("默认分享的图片url")
//                    .addShareMedia(SHARE_MEDIA.WEICHAT, SHARE_MEDIA.WEICHATCIRCLE, SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QQZONE, SHARE_MEDIA.MESSAGE)
//                            //如果要自定义分享的图标，可以通过下面的方式进行设置，使用的默认分享图标，注释该方法即可
//                            //.setShareWayIconMap(iconMap)
//                    .setQQAppId("自己申请的appId")
//                    .setWeiboAppId("自己申请的appId")
//                    .setWechatAppId("自己申请的appId")
//                    .setSinaRedirectUrl("https://api.weibo.com/oauth2/default.html")
//                    .setScope("email,direct_messages_read,direct_messages_write,\"\n" +
//                            "            + \"friendships_groups_read,friendships_groups_write,statuses_to_me_read,\"\n" +
//                            "            + \"follow_app_official_microblog,\" + \"invitation_write")
//                    .setDefImageUrlId(R.drawable.ic_launcher);
    }
}